package com.record.ccod;

import com.elite.groovy.kh.KHDBConfig;
import com.elite.groovy.kh.KHUtil;
import com.elite.groovy.util.Util;
import com.record.utils.RecUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

public class CCODUtils_WaRTC {
    private static final Log log = LogFactory.getLog(CCODUtils_WaRTC.class);
    private static JSONObject rec_Config = new JSONObject();
    private static String queryEncryptionURL = "";
    private static String queryURL = "";
    private static String queryRecordURL = "";
    private static String ProxyIP = "";
    private static String ProxyPort = "";
    private static String amrconvertcmd = "";

    // 2-查询呼叫明细数据
    public static String doCCODQuery(JdbcTemplate jt, HttpServletResponse response, String requestType, String entId, String recData, String startTime, String endTime, String pageNum, String multimode) {
        String res_RecordStr = "";

        try {

            // 初始化参数
            rec_Config = KHUtil.SFIsNull(rec_Config.toString()) ? JSONObject.fromObject(KHDBConfig.getParamConfig(jt, "REC_CFG-" + entId)) : rec_Config;

            queryEncryptionURL = KHUtil.GetSFJV(rec_Config, "CCODURL") + "/customWebservice/mvc/Encryption/queryEncryption.do";
            queryURL = KHUtil.GetSFJV(rec_Config, "CCODURL") + "/customWebservice/mvc/sessionDetail/query.do";
            queryRecordURL = KHUtil.GetSFJV(rec_Config, "CCODURL") + "/customWebservice/mvc/sessionDetail/queryRecord.do";
            ProxyIP = KHUtil.GetSFJV(rec_Config, "ProxyIP");
            ProxyPort = KHUtil.GetSFJV(rec_Config, "ProxyPort");
            amrconvertcmd = KHUtil.GetSFJV(rec_Config, "amrconvertcmd");

            // 获取queryEncryption
            JSONObject queryEncryptionJson = doQueryEncryption(jt, requestType);
            String Signature = KHUtil.GetSFJV(queryEncryptionJson, "Signature");
            String Authorization = KHUtil.GetSFJV(queryEncryptionJson, "Authorization");
            log.debug("数据接口鉴权 Signature:" + Signature + " Authorization:" + Authorization);

            // 1-识别调用方式对应的URL
            String callURL = "";
            if (requestType.equals("query")) {
                callURL = queryURL;
            } else {
                callURL = queryRecordURL;
            }
            log.debug("调用CCOD接口 URL:" + callURL);

            // 2-处理入参信息
            Map<String, String> URLParamsMap = new HashMap<String, String>();
            URLParamsMap.put("entId", entId);
            URLParamsMap.put("pageNum", KHUtil.isNull(pageNum) ? "1" : pageNum);

            // 2-1-sessionId
            if (!KHUtil.isNull(recData)) {
                String[] sessionIds = recData.split(":");
                String sessionId10 = new BigInteger(sessionIds[0], 16).toString(10);
                URLParamsMap.put("sessionId", sessionId10);
            }

            // 2-2-startTime
            if (!KHUtil.isNull(startTime)) {
                URLParamsMap.put("startTime", startTime);
            }

            // 2-3-endTime
            if (!KHUtil.isNull(endTime)) {
                URLParamsMap.put("endTime", endTime);
            }

            // 查询CCOD接口地址
            callURL = callURL + "?" + KHUtil.urlencode(URLParamsMap, "") + "&Signature=" + Signature;
            log.debug("调用CCOD接口 URL参数:" + callURL);

            Map<String, String> headerMap = new HashMap<String, String>();
            headerMap.put("Content-Type", "application/json;charset=utf-8");
            headerMap.put("Authorization", Authorization);
            log.debug("调用CCOD接口 headerMap:" + headerMap);

            String queryRes = Util.doHttpPostUseHead(callURL, "", "UTF-8", 10000, 0, headerMap, "", ProxyIP, Integer.parseInt(ProxyPort), !KHUtil.isNull(ProxyIP));
            log.debug("调用CCOD接口 返回:" + queryRes);

            // queryRecord模式multimode非空是DYN录音调听或下载,按DYN模式返回录音信息
            if (requestType.equalsIgnoreCase("queryRecord")) {
                JSONObject queryRes_Json = JSONObject.fromObject(queryRes);
                JSONArray queryRes_Data = queryRes_Json.getJSONArray("result");

                // multimode=1 DYN获取XML格式录音
                if (multimode.equals("1")) {

                    String queryRes_XML = "<recordFiles>";
                    for (int i = 0; i < queryRes_Data.size(); i++) {
                        String recordName = KHUtil.GetSFJV(queryRes_Data.getJSONObject(i), "recordName");

                        if (!KHUtil.isNull(recordName)) {
                            queryRes_XML = queryRes_XML + "<recordFile><recordName>" + KHUtil.GetSFJV(queryRes_Data.getJSONObject(i), "recordName") + "</recordName></recordFile>";
                        } else {
                            log.warn("解析转换录音文件路径到XML时,平台返回录音文件路径异常");
                        }
                    }

                    res_RecordStr = queryRes_XML + "</recordFiles>";

                } else if (KHUtil.isNull(multimode)) {

                    for (int i = 0; i < queryRes_Data.size(); i++) {
                        String recordName = KHUtil.GetSFJV(queryRes_Data.getJSONObject(i), "recordName");

                        if (!KHUtil.isNull(recordName)) {
                            res_RecordStr = recordName;
                            break;
                        } else {
                            log.warn("解析转换录音文件路径到时,平台返回录音文件路径异常");
                        }
                    }
                } else {
                    res_RecordStr = queryRes;
                }
            } else {
                res_RecordStr = queryRes;
            }
            log.debug("解析转换录音 结果:" + res_RecordStr);

            // 根据返回类型判断是否是链接 链接是否需要转码
            if (res_RecordStr.startsWith("http://")) {

                if (!KHUtil.isNull(amrconvertcmd)) {
                    RecUtils.ConvertAmrAudio(jt, response, entId, res_RecordStr);
                    return "";
                } else {
                    response.sendRedirect(res_RecordStr);
                    return "";
                }
            }

        } catch (Exception e) {
            log.error("CCOD(青牛WaRTC)录音平台录音异常", e);
        }
        log.debug("res_RecordStr:" + res_RecordStr);

        return res_RecordStr;

    }

    // 1-数据接口鉴权
    public static JSONObject doQueryEncryption(JdbcTemplate jt, String requestType) throws Exception {

        // 获取queryEncryption
        String callEncryptionURL = queryEncryptionURL + "?request=" + KHUtil.encode(requestType);
        log.debug("1-数据接口鉴权 URL:" + callEncryptionURL);

        Map<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("Content-Type", "application/json");
        log.debug("1-数据接口鉴权 headerMap:" + headerMap);

        String queryEncryptionRes = Util.doHttpPostUseHead(callEncryptionURL, "", "UTF-8", 10000, 0, headerMap, "", ProxyIP, Integer.parseInt(ProxyPort), !KHUtil.isNull(ProxyIP));

        JSONObject queryEncryptionJson = JSONObject.fromObject(queryEncryptionRes);
        log.debug("1-数据接口鉴权 Res Json:" + queryEncryptionJson);

        return queryEncryptionJson;

    }
}
